<script setup>
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user.js'
import { readBook, addRead } from '@/api/book/index.js'
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue';
const { params } = useRoute()
const router = useRouter()
const { userInfo } = useUserStore()
const cInfo = ref({})

onMounted(() => {
  readBook({ novelId: params.id, chapterId: params.cid, userId: userInfo.id })
    .then(res => {
      cInfo.value = res
      // 获取到章节在增加浏览量
      addRead({ novelId: params.id, chapterId: params.cid})
    })
    .catch((err) => {
      message.error(err || '请先登录')
      setTimeout(() => {
        router.push('/')
      }, 2000)
    })
})


// 返回书籍详情页
const handleBack = () => {
  router.push(`/shuku/${cInfo.value.novelId}`)
}
// 上一章
const previous = () => {
  if(!cInfo.value.previousChapterId) {
    return message.error('上一章不存在')
  }
  readBook({ novelId: params.id, chapterId: cInfo.value.previousChapterId, userId: userInfo.id })
  .then(res => {
    // 获取到章节在增加浏览量
    addRead({ novelId: params.id, chapterId: cInfo.value.previousChapterId})
    cInfo.value = res

  })
  document.body.scrollIntoView()
  router.push(`/shuku/${cInfo.value.novelId}/${cInfo.value.previousChapterId}`)
}
// 下一章
const next = () => {
  if(!cInfo.value.nextChapterId) {
    return message.error('已经是最后一章了')
  }
  readBook({ novelId: params.id, chapterId: cInfo.value.nextChapterId, userId: userInfo.id })
  .then(res => {
    //获取到章节在增加浏览量
    addRead({ novelId: params.id, chapterId: cInfo.value.nextChapterId})
    cInfo.value = res
  }).catch(err => {
    message.error(err || '读书失败')
  })
  document.body.scrollIntoView()
  router.push(`/shuku/${cInfo.value.novelId}/${cInfo.value.nextChapterId}`)
}
</script>
<template>
<div class="wrapper">
  <div class="back"> <a-button @click="handleBack">返回书籍</a-button> </div>
  <div class="con">
    <h2 class="title">{{ cInfo.chapterName }}</h2>
    <div class="content" v-html="cInfo.chapterContentHtml"></div>
    <div class="btn-board">
      <a-button type="primary"  shape="round" v-if="cInfo.chapterNo !== 1" ghost style="margin-right: 25px;" @click="previous">上一章</a-button>
      <a-button type="primary" shape="round" @click="next" :disabled="cInfo.nextChapterId === null">{{ cInfo.nextChapterId === null ? '你已经读完啦' : '下一章' }}</a-button>
    </div>
  </div>
</div>
</template>
<style lang="less" scoped>
.wrapper {
  padding: 30px;
  .back {
    position: fixed;
  }
  .con {
    width: 860px;
    margin: 0 auto;
    .title {
      text-align: center;
      font-size: 30px;
    }
    .btn-board {
      text-align: center;

    }
  }
}
</style>
<style lang="less">
.content {
  p {
    font-size: 20px;
  }
}
</style>
